package com.yugao.fintech.libra.workflow.controller;

import com.yugao.fintech.meheco.core.domain.ResultVO;
import com.yugao.fintech.meheco.core.web.controller.BaseController;
import com.yugao.fintech.draper.security.annotation.InnerApi;
import com.yugao.fintech.libra.workflow.api.model.FlowInfo;
import com.yugao.fintech.libra.workflow.domain.dto.FlowProcDefDto;
import com.yugao.fintech.libra.workflow.domain.vo.FlowSaveXmlVo;
import com.yugao.fintech.libra.workflow.service.IFlowDefinitionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;


@RestController
@RequestMapping("/definition")
@Tag(name = "流程定义")
public class FlowDefinitionController extends BaseController {
    @Autowired
    private IFlowDefinitionService flowDefinitionService;

    @GetMapping(value = "/list")
    @Operation(description = "流程定义列表", response = FlowProcDefDto.class)
    public com.yugao.fintech.meheco.core.web.domain.AjaxResult list(@ApiParam(value = "当前页码", required = true) @RequestParam Integer pageNum,
                                                                    @ApiParam(value = "每页条数", required = true) @RequestParam Integer pageSize,
                                                                    @ApiParam(value = "流程名称", required = false) @RequestParam(required = false) String name,
                                                                    @ApiParam(value = "流程分类", required = false) @RequestParam(required = false) String category) {
        return com.yugao.fintech.meheco.core.web.domain.AjaxResult.success(flowDefinitionService.list(name, category, pageNum, pageSize));
    }


    @Operation(description = "导入流程文件", summary = "上传bpmn20的xml文件")
    @PostMapping("/import")
    public com.yugao.fintech.meheco.core.web.domain.AjaxResult importFile(@RequestParam(required = true) String name,
                                                                          @RequestParam(required = true) String category,
                                                                          MultipartFile file) {
        InputStream in = null;
        try {
            in = file.getInputStream();
            flowDefinitionService.importFile(name, category, in);
        } catch (Exception e) {
            logger.error("导入失败:", e);
            return com.yugao.fintech.meheco.core.web.domain.AjaxResult.success(e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error("关闭输入流出错", e);
            }
        }
        return com.yugao.fintech.meheco.core.web.domain.AjaxResult.success("导入成功");
    }


    @Operation(description = "读取xml文件")
    @GetMapping("/readXml/{deployId}")
    public com.yugao.fintech.meheco.core.web.domain.AjaxResult readXml(@ApiParam(value = "流程定义id") @PathVariable(value = "deployId") String deployId) {
        try {
            return com.yugao.fintech.meheco.core.web.domain.AjaxResult.success("", flowDefinitionService.readXml(deployId));
        } catch (Exception e) {
            return com.yugao.fintech.meheco.core.web.domain.AjaxResult.error("加载xml文件异常");
        }
    }

    @Operation(description = "保存流程设计器内的xml文件")
    @PostMapping("/save")
    public com.yugao.fintech.meheco.core.web.domain.AjaxResult save(@RequestBody FlowSaveXmlVo vo) {
        InputStream in = null;
        try {
            in = new ByteArrayInputStream(vo.getXml().getBytes(StandardCharsets.UTF_8));
            flowDefinitionService.importFile(vo.getName(), vo.getCategory(), in);
        } catch (Exception e) {
            logger.error("导入失败:", e);
            return com.yugao.fintech.meheco.core.web.domain.AjaxResult.success(e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error("关闭输入流出错", e);
            }
        }
        return com.yugao.fintech.meheco.core.web.domain.AjaxResult.success("导入成功");
    }

    @InnerApi
    @PostMapping("/inner/start")
    public ResultVO<String> startProcessInner(@RequestBody FlowInfo flowInfo) {
        flowDefinitionService.startProcess(flowInfo);
        return ResultVO.success("流程启动成功");
    }

    @Operation(description = "激活或挂起流程定义")
    @PutMapping(value = "/updateState")
    public com.yugao.fintech.meheco.core.web.domain.AjaxResult updateState(@ApiParam(value = "1:激活,2:挂起", required = true) @RequestParam Integer state,
                                                                           @ApiParam(value = "流程部署ID", required = true) @RequestParam String deployId) {
        flowDefinitionService.updateState(deployId, state);
        return com.yugao.fintech.meheco.core.web.domain.AjaxResult.success();
    }

    @Operation(description = "删除流程")
    @DeleteMapping(value = "/delete")
    public com.yugao.fintech.meheco.core.web.domain.AjaxResult delete(@ApiParam(value = "流程部署ID") @RequestParam(required = true) String deployId) {
        flowDefinitionService.delete(deployId);
        return com.yugao.fintech.meheco.core.web.domain.AjaxResult.success();
    }
}